package edu.usm.roberge.ui;

import java.util.concurrent.ExecutionException;

import javax.swing.SwingWorker;

import edu.usm.roberge.model.StockStore;
import edu.usm.roberge.model.StockStore.PickedStock;

/**
 * Worker that gets executed when the user presses the "Pick Stock" button
 * Runs either the most stocks owned or most profit computation
 */
public class CalculationWorker extends SwingWorker<PickedStock, Void> {

	private final StockStore store;
	private final Listener listener;
	private final double investmentAmount;
	private final Algorithm algorithm;
	
	public interface Listener {
		void onSelectedStock(PickedStock data);
	}
	
	enum Algorithm {
		MOST_SHARES, MOST_PROFIT
	}

	public CalculationWorker(double investmentAmount, StockStore store, Listener listener, Algorithm algorithm) {
		this.investmentAmount = investmentAmount;
		this.store = store;
		this.listener = listener;
		this.algorithm = algorithm;
	}
	
	@Override
	protected PickedStock doInBackground() throws Exception {
		if (algorithm.equals(Algorithm.MOST_SHARES)) {
			return store.pickStockByMostOwned(investmentAmount);
		} else {
			return store.pickStockByMostProfit(investmentAmount);
		}
	}

	@Override
	protected void done() {
		try {
			if (get() == null) {
				return;
			}
			
			listener.onSelectedStock(get());
		} catch (InterruptedException e) {
		} catch (ExecutionException e) {
		}
	}

}
